package com.stylefeng.guns.modular.area.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.controller.BaseController;
import com.stylefeng.guns.common.node.ZTreeNode;
import com.stylefeng.guns.common.persistence.dao.DeptMapper;
import com.stylefeng.guns.common.persistence.dao.RoleMapper;
import com.stylefeng.guns.common.persistence.dao.UserMapper;
import com.stylefeng.guns.common.persistence.model.Dept;
import com.stylefeng.guns.common.persistence.model.Role;
import com.stylefeng.guns.common.persistence.model.User;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.area.dao.BdapAreaCellRefMapper;
import com.stylefeng.guns.modular.area.dao.BdapAreaMapper;
import com.stylefeng.guns.modular.area.dao.BdapAreaTypeMapper;
import com.stylefeng.guns.modular.area.dao.BdapCellInfoMonthMapper;
import com.stylefeng.guns.modular.area.dao.BdapCityDistrictMapper;
import com.stylefeng.guns.modular.area.dao.BdapSubAreaMapper;
import com.stylefeng.guns.modular.area.dao.BdapUserAreaMapper;
import com.stylefeng.guns.modular.area.model.BdapArea;
import com.stylefeng.guns.modular.area.model.BdapAreaCellRef;
import com.stylefeng.guns.modular.area.model.BdapAreaType;
import com.stylefeng.guns.modular.area.model.BdapCellInfoMonth;
import com.stylefeng.guns.modular.area.model.BdapCityDistrict;
import com.stylefeng.guns.modular.area.model.BdapSubArea;
import com.stylefeng.guns.modular.area.model.BdapUserArea;
import com.stylefeng.guns.modular.map.model.Point;
import com.stylefeng.guns.modular.util.EntityUtil;
import com.stylefeng.guns.modular.util.MapUtil;
import com.stylefeng.guns.modular.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 区域管理控制器
 *
 * @author liqi
 * @Date 2017-11-06 15:37:06
 */
@Controller
@RequestMapping("/area")
public class AreaController extends BaseController {

	private String PREFIX = "/area/";
	@Autowired
	private BdapAreaMapper areaMapper;
	@Autowired
	private BdapSubAreaMapper subAreaMapper;
	@Autowired
	private BdapCellInfoMonthMapper cellMapper;
	@Autowired
	private BdapCityDistrictMapper cityDistrictMapper;
	@Autowired
	private BdapAreaTypeMapper areaTypeMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private BdapUserAreaMapper userAreaMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private BdapAreaCellRefMapper areaCellMapper;

	/**
	 * 跳转到区域管理首页
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "area.html";
	}

	/**
	 * 跳转到添加区域管理
	 * 查询地市区县下拉框
	 * 查询区域类型下拉框
	 */
	@RequestMapping("/area_add")
	public String areaAdd(Model model) {
		List<BdapCityDistrict> cityDistrictList = cityDistrictMapper.selectList(null);
		Map<String, List<String>> cityDistrictMap = EntityUtil.getCityDistrictMap(cityDistrictList);
		String cityDistrictJson = JSON.toJSONString(cityDistrictMap).replaceAll("\"", "\'");
		model.addAttribute("cityDistrictJson", cityDistrictJson);
		List<BdapAreaType> areaTypeList = areaTypeMapper.selectList(null);
		String areaTypeJson = JSON.toJSONString(areaTypeList).replaceAll("\"", "\'");
		model.addAttribute("areaTypeJson", areaTypeJson);
		return PREFIX + "area_add.html";
	}

	/**
	 * 跳转到修改区域管理
	 * 根据id查询当前区域信息
	 * 查询地市区县下拉框
	 * 查询区域类型下拉框
	 */
	@RequestMapping("/area_update/{areaId}")
	public String areaUpdate(@PathVariable long areaId, Model model) {
		BdapArea area = areaMapper.selectById(areaId);
		model.addAttribute("area", area);
		List<BdapCityDistrict> cityDistrictList = cityDistrictMapper.selectList(null);
		Map<String, List<String>> cityDistrictMap = EntityUtil.getCityDistrictMap(cityDistrictList);
		String cityDistrictJson = JSON.toJSONString(cityDistrictMap).replaceAll("\"", "\'");
		model.addAttribute("cityDistrictJson", cityDistrictJson);
		List<BdapAreaType> areaTypeList = areaTypeMapper.selectList(null);
		String areaTypeJson = JSON.toJSONString(areaTypeList).replaceAll("\"", "\'");
		model.addAttribute("areaTypeJson", areaTypeJson);
		return PREFIX + "area_edit.html";
	}

	/**
	 * 跳转到区域详情
	 */
	@RequestMapping("/area_detail/{areaId}")
	public String areaDetail(@PathVariable long areaId, Model model) {
		model.addAttribute(areaId);
		return PREFIX + "area_detail.html";
	}

	/**
	 * 跳转到区域授权
	 * 根据id查询当前区域信息
	 */
	@RequestMapping("/area_auth/{areaId}")
	public String areaAuth(@PathVariable long areaId, Model model) {
		BdapArea area = areaMapper.selectById(areaId);
		model.addAttribute("area", area);
		return PREFIX + "area_auth.html";
	}

	/**
	 * 获取区域管理列表
	 * 判断当前用户是否是超级管理员
	 * 如果是超级管理员，显示所有区域
	 * 如果不是超级管理员，显示用户授权区域
	 * 显示用户关注区域
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(String condition) {
		EntityWrapper<BdapArea> areaEntityWrapper = new EntityWrapper<>();
		EntityWrapper<BdapUserArea> userAreaEntityWrapper = new EntityWrapper<>();
		if (ToolUtil.isNotEmpty(condition)) {
			areaEntityWrapper.like("name", "%" + condition + "%");
		}
		long impAreaId = 0L;
		int userId = ShiroKit.getUser().getId();
		userAreaEntityWrapper.eq("userId", userId);
		List<BdapUserArea> userAreaList = userAreaMapper.selectList(userAreaEntityWrapper);
		List<Long> areaIdList = new ArrayList<Long>();
		for (BdapUserArea userArea : userAreaList) {
			areaIdList.add(userArea.getAreaid());
			if (userArea.getIsImportant() != null && userArea.getIsImportant() == 1) {
				impAreaId = userArea.getAreaid();
			}
		}
		if (!ShiroKit.isAdmin()) {
			if (areaIdList.size() > 0) {
				areaEntityWrapper.in("id", areaIdList);
			} else {
				return null;
			}
		}
		List<BdapArea> areaListResult = areaMapper.selectList(areaEntityWrapper);
		List<BdapArea> areaList = new ArrayList<BdapArea>();
		for (BdapArea area : areaListResult) {
			if (area.getId().equals(impAreaId)) {
				area.setIsImportant(1);
			}
			areaList.add(area);
		}
		return areaList;
	}

	/**
	 * 设置关注
	 * 如果是增加关注，如果是超级管理员，增加该用户区域记录并设置关注，删除该用户其他区域记录，
	 *             如果不是超级管理员，更新该用户区域记录并设置关注，更新该用户其他区域记录并设置不关注
	 * 如果是取消关注，如果是超级管理员，删除该用户区域记录，
	 *             如果不是超级管理员，更新该用户区域记录并设置不关注
	 */
	@RequestMapping(value = "/setImp")
	@ResponseBody
	public Object setImp(long areaId, String handle) {
		EntityWrapper<BdapUserArea> userAreaEntityWrapper = new EntityWrapper<>();
		ShiroUser shiroUser = ShiroKit.getUser();
		userAreaEntityWrapper.eq("userId", shiroUser.getId());
		userAreaEntityWrapper.eq("areaId", areaId);
		if ("add".equals(handle)) {
			EntityWrapper<BdapUserArea> userAreaEntityWrapper2 = new EntityWrapper<>();
			userAreaEntityWrapper2.eq("userId", shiroUser.getId());
			userAreaEntityWrapper2.ne("areaId", areaId);
			BdapUserArea userArea = new BdapUserArea();
			userArea.setIsImportant(1);
			if (!ShiroKit.isAdmin()) {
				userAreaMapper.update(userArea, userAreaEntityWrapper);
				userArea = new BdapUserArea();
				userArea.setIsImportant(0);
				userAreaMapper.update(userArea, userAreaEntityWrapper2);
			} else {
				userArea.setAreaid(areaId);
				userArea.setUserid(shiroUser.getId());
				userAreaMapper.insert(userArea);
				userAreaMapper.delete(userAreaEntityWrapper2);
			}
		} else {
			BdapUserArea userArea = new BdapUserArea();
			userArea.setIsImportant(0);
			if (!ShiroKit.isAdmin()) {
				userAreaMapper.update(userArea, userAreaEntityWrapper);
			} else {
				userAreaMapper.delete(userAreaEntityWrapper);
			}
		}
		return SUCCESS_TIP;
	}

	/**
	 * 新增区域管理
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add(BdapArea area) {
		ShiroUser shiroUser = ShiroKit.getUser();
		area.setUserid(shiroUser.getId());
		return areaMapper.insert(area);
	}

	/**
	 * 删除区域管理
	 * 删除区域表中该区域的记录
	 * 删除子区域表中该区域的记录
	 * 删除用户区域表中该区域的记录
	 * 删除区域小区表中该区域的记录
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(long areaId) {
		EntityWrapper<BdapSubArea> subAreaEntityWrapper = new EntityWrapper<>();
		subAreaEntityWrapper.eq("pid", areaId);
		subAreaMapper.delete(subAreaEntityWrapper);
		EntityWrapper<BdapAreaCellRef> areaCellWrapper = new EntityWrapper<>();
		areaCellWrapper.eq("areaid", areaId);
		areaCellMapper.delete(areaCellWrapper);
		EntityWrapper<BdapUserArea> userAreaEntityWrapper = new EntityWrapper<>();
		userAreaEntityWrapper.eq("areaid", areaId);
		userAreaMapper.delete(userAreaEntityWrapper);
		return areaMapper.deleteById(areaId);
	}

	/**
	 * 修改区域管理
	 */

	@RequestMapping(value = "/update")
	@ResponseBody
	public Object update(BdapArea area) {
		return areaMapper.updateById(area);
	}

	/**
	 * 跳转到添加子区域管理
	 */
	@RequestMapping("/sub/area_add/{areaId}")
	public String subAreaAdd(@PathVariable long areaId, Model model) {
		BdapArea area = areaMapper.selectById(areaId);
		model.addAttribute("area", area);
		return PREFIX + "subArea_add.html";
	}

	/**
	 * 跳转到修改子区域管理
	 * 根据id查询当前子区域信息
	 * 查询当前子区域小区信息
	 */
	@RequestMapping("/sub/area_update/{subAreaId}")
	public String subAreaUpdate(@PathVariable long subAreaId, Model model) {
		BdapSubArea subArea = subAreaMapper.selectById(subAreaId);
		String[] lacCi = subArea.getLacCi().split(";");
		EntityWrapper<BdapCellInfoMonth> cellWrapper = new EntityWrapper<>();
		cellWrapper.in("concat(concat(lac,','),ci)", lacCi);
		List<BdapCellInfoMonth> cellList = cellMapper.selectList(cellWrapper);
		BdapArea area = areaMapper.selectById(subArea.getPid());
		model.addAttribute("subArea", subArea);
		model.addAttribute("area", area);
		String cellJson = JSON.toJSONString(cellList).replaceAll("\"", "\'");
		model.addAttribute("cellJson", cellJson);
		return PREFIX + "subArea_edit.html";
	}

	/**
	 * 获取子区域管理列表
	 * 根据pid查询当前区域所有子区域
	 */
	@RequestMapping(value = "/sub/list/{areaId}")
	@ResponseBody
	public Object subList(@PathVariable long areaId, String condition) {
		BdapArea area = areaMapper.selectById(areaId);
		EntityWrapper<BdapSubArea> subAreaEntityWrapper = new EntityWrapper<>();
		subAreaEntityWrapper.eq("pid", areaId);
		if (ToolUtil.isNotEmpty(condition)) {
			subAreaEntityWrapper.like("name", "%" + condition + "%");
		}
		List<BdapSubArea> subAreaList = subAreaMapper.selectList(subAreaEntityWrapper);
		for (BdapSubArea subArea : subAreaList) {
			subArea.setpName(area.getName());
		}
		return subAreaList;
	}

	/**
	 * 新增子区域管理
	 * 新增子区域记录
	 * 新增区域小区记录
	 */
	@RequestMapping(value = "/sub/add")
	@ResponseBody
	public Object subAdd(BdapSubArea subArea) {
		ShiroUser shiroUser = ShiroKit.getUser();
		subArea.setUserid(shiroUser.getId());
		subAreaMapper.insert(subArea);
		for (String lacCi : subArea.getLacCi().split(";")) {
			BdapAreaCellRef areaCell = new BdapAreaCellRef();
			areaCell.setAreaid(subArea.getPid());
			areaCell.setSubAreaid(subArea.getId());
			areaCell.setLacHexCode(lacCi.split(",")[0]);
			areaCell.setCiHexCode(lacCi.split(",")[1]);
			areaCellMapper.insert(areaCell);
		}
		return SUCCESS_TIP;
	}

	/**
	 * 删除子区域管理
	 * 删除子区域表中该子区域的记录
	 * 删除区域小区表中该子区域的记录
	 */
	@RequestMapping(value = "/sub/delete")
	@ResponseBody
	public Object subDelete(long subAreaId) {
		EntityWrapper<BdapAreaCellRef> areaCellWrapper = new EntityWrapper<>();
		areaCellWrapper.eq("sub_areaid", subAreaId);
		areaCellMapper.delete(areaCellWrapper);
		return subAreaMapper.deleteById(subAreaId);
	}

	/**
	 * 修改子区域管理
	 * 修改子区域表中该区域的记录
	 * 删除区域小区表中该区域的记录
	 * 插入区域小区记录
	 */
	@RequestMapping(value = "/sub/update")
	@ResponseBody
	public Object subUpdate(BdapSubArea subArea) {
		EntityWrapper<BdapAreaCellRef> areaCellWrapper = new EntityWrapper<>();
		areaCellWrapper.eq("sub_areaid", subArea.getId());
		areaCellMapper.delete(areaCellWrapper);
		for (String lacCi : subArea.getLacCi().split(";")) {
			BdapAreaCellRef areaCell = new BdapAreaCellRef();
			areaCell.setAreaid(subArea.getPid());
			areaCell.setSubAreaid(subArea.getId());
			areaCell.setLacHexCode(lacCi.split(",")[0]);
			areaCell.setCiHexCode(lacCi.split(",")[1]);
			areaCellMapper.insert(areaCell);
		}
		return subAreaMapper.updateById(subArea);
	}

	/**
	 * 查询范围内小区
	 * 根据地市名称查找所有小区
	 * 获取范围内的小区
	 */
	@RequestMapping(value = "/sub/listCell")
	@ResponseBody
	public Object subListCell(String lonLat, String city) {
		List<List<Point>> polygonList = MapUtil.getPoints(lonLat);
		EntityWrapper<BdapCellInfoMonth> cellWrapper = new EntityWrapper<>();
		cellWrapper.eq("city_name", city);
		List<BdapCellInfoMonth> bcimList = cellMapper.selectList(cellWrapper);
		List<BdapCellInfoMonth> newbcimList = new ArrayList<BdapCellInfoMonth>();
		for (BdapCellInfoMonth bcim : bcimList) {
			String lon = MapUtil.offset(bcim.getLon(), "0.01185");
			String lat = MapUtil.offset(bcim.getLat(), "0.00328");
			Point point = new Point(Double.parseDouble(lon), Double.parseDouble(lat));
			for (List<Point> pointList : polygonList) {
				boolean isInPolygon = MapUtil.isPointInPolygon(pointList, point);
				if (isInPolygon) {
					newbcimList.add(bcim);
					break;
				}
			}
		}
		return newbcimList;
	}

	/**
	 * 获取用户列表
	 * 获取非超级管理员用户
	 * 获取非超级管理员用户的部门
	 */
	@RequestMapping(value = "/userTreeList/{areaId}")
	@ResponseBody
	public List<ZTreeNode> userTreeList(@PathVariable long areaId) {
		EntityWrapper<Role> roleEntityWrapper = new EntityWrapper<>();
		roleEntityWrapper.eq("tips", Const.ADMIN_NAME);
		Role admin = roleMapper.selectList(roleEntityWrapper).get(0);

		EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
		userEntityWrapper.ne("status", 3);
		userEntityWrapper.and();
		userEntityWrapper.ne("roleid", admin.getId());
		List<User> userList = userMapper.selectList(userEntityWrapper);

		EntityWrapper<BdapUserArea> userAreaWrapper = new EntityWrapper<>();
		userAreaWrapper.eq("areaid", areaId);
		List<BdapUserArea> userAreaList = userAreaMapper.selectList(userAreaWrapper);

		List<ZTreeNode> ztnList = new ArrayList<ZTreeNode>();
		List<Integer> deptIdList = new ArrayList<Integer>();
		for (User user : userList) {
			ZTreeNode ztn = new ZTreeNode();
			ztn.setId((long) user.getId());
			ztn.setpId(Long.parseLong(StringUtil.nullToDefault(user.getDeptid(), "0")));
			ztn.setName(user.getName());
			for (BdapUserArea userArea : userAreaList) {
				if (user.getId().equals(userArea.getUserid())) {
					ztn.setChecked(true);
				}
			}
			ztnList.add(ztn);
			if (ToolUtil.isNotEmpty(user.getDeptid())) {
				deptIdList.add(user.getDeptid());
			}
		}

		EntityWrapper<Dept> deptWrapper = new EntityWrapper<>();
		deptWrapper.in("id", deptIdList);
		List<Dept> deptList = deptMapper.selectList(deptWrapper);

		for (Dept dept : deptList) {
			ZTreeNode ztn = new ZTreeNode();
			ztn.setId((long) dept.getId());
			ztn.setpId(Long.parseLong(StringUtil.nullToDefault(dept.getPid(), "0")));
			ztn.setName(dept.getSimplename());
			ztnList.add(ztn);
		}
		return ztnList;
	}

	/**
	 * 用户区域授权
	 * 增加该区域选中用户的区域用户记录
	 * 删除该区域除超级管理员的未选中用户的区域用户记录
	 */
	@RequestMapping(value = "/auth")
	@ResponseBody
	public Object setAuth(long areaId, String userIds) {
		EntityWrapper<Role> roleEntityWrapper = new EntityWrapper<>();
		roleEntityWrapper.eq("tips", Const.ADMIN_NAME);
		Role role = roleMapper.selectList(roleEntityWrapper).get(0);
		EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
		userEntityWrapper.eq("roleid", role.getId()).and().ne("status", 3);
		List<User> adminList = userMapper.selectList(userEntityWrapper);
		List<Integer> adminIdList = new ArrayList<>();
		for (User user : adminList) {
			adminIdList.add(user.getId());
		}
		EntityWrapper<BdapUserArea> userAreaWrapper = new EntityWrapper<>();
		if (null == userIds || "".equals(userIds)) {
			userAreaWrapper.eq("areaid", areaId).and().notIn("userid", adminIdList);
			userAreaMapper.delete(userAreaWrapper);
		} else {
			String[] userIdArr = userIds.split(",");
			userEntityWrapper = new EntityWrapper<>();
			userEntityWrapper.in("id", userIdArr).and().ne("status", 3);
			List<User> userList = userMapper.selectList(userEntityWrapper);
			List<Integer> userIdList = new ArrayList<>();
			for (User user : userList) {
				BdapUserArea userArea = new BdapUserArea();
				userArea.setAreaid(areaId);
				userArea.setUserid(user.getId());
				userAreaMapper.insert(userArea);
				userIdList.add(user.getId());
			}
			userAreaWrapper.eq("areaid", areaId).and().notIn("userid", userIdList).and().notIn("userid", adminIdList);
			userAreaMapper.delete(userAreaWrapper);
		}
		return SUCCESS_TIP;
	}
}
